//
//  CategoryViewController.m
//  quanminzhekou
//
//  Created by zxl on 15/1/8.
//  Copyright (c) 2015年 zhongqinglongtu. All rights reserved.
//

#import "CategoryViewController.h"
#import "CommonTableViewCell.h"
#import "CategorySelectView.h"
#import "CommonCellViewModel.h"
#import "DetailViewController.h"

@interface CategoryViewController ()
@property (nonatomic) UIControl             *closeCtrl;
@property (nonatomic) NSArray               *categoryArr;
@property (nonatomic) CategorySelectView    *selectView;
@property (nonatomic) NSInteger             showSubCategoryRow;
@property (nonatomic) CategoryFilterView    *filterView;

@property (nonatomic) NSMutableArray        *dataArr;
@property (nonatomic) MKNetworkOperation    *categoryOperation;
@end

@implementation CategoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _dataArr = [NSMutableArray new];
    
    self.titleLab.text = self.title;
    
    //    NSString* file = [[NSBundle mainBundle] pathForResource:@"CategoryList" ofType:@".plist"];
    //    _categoryArr = [NSArray arrayWithContentsOfFile:file];
    
    NSString* file1 = [[NSBundle mainBundle] pathForResource:@"Category" ofType:@""];
    NSString* content =  [NSString stringWithContentsOfFile:file1 encoding:NSUTF8StringEncoding error:nil];
    NSData* data = [content dataUsingEncoding:NSUTF8StringEncoding];
    
    NSArray* arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    _categoryArr = [NSArray arrayWithArray:arr];
    
    _showSubCategoryRow = 0;
    [self.tableView reloadData];
    
    self.categoryPos = [self getPositionSubCategoryPoint];
    
    self.engineModel.zqStr = @"1";
    if (![self.title isEqualToString:@"全部"]) {
        self.engineModel.flPoint = self.categoryPos;
    }
    
    [self addObserver:self forKeyPath:@"title" options:0 context:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectSubCategory:) name:@"NotificationOfSelectSubCategoryTitle" object:nil];
    
    [self setupSortViewBtnsHandler];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self updateTitleViewFrame];
    
    self.closeCtrl.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds));
    self.selectView.frame = CGRectMake(0, 57, CGRectGetWidth([UIScreen mainScreen].bounds), 0);
    self.filterView.frame = CGRectMake(CGRectGetMinX(self.sortView.frame), CGRectGetMaxY(self.sortView.frame) - 1, CGRectGetWidth(self.sortView.frame), 0);
    [self.filterView layoutCategoryFilterViewSubviews];
    
    [self.view bringSubviewToFront:self.closeCtrl];
    [self.view bringSubviewToFront:self.sortView];
    [self.view bringSubviewToFront:self.selectView];
    [self.view bringSubviewToFront:self.filterView];
}

- (void)dealloc
{
    [self.categoryOperation cancel];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NotificationOfSelectSubCategoryTitle" object:nil];
    [self removeObserver:self forKeyPath:@"title"];
}

- (UILabel*)titleLab {
    if (nil == _titleLab) {
        _titleLab = [[UILabel alloc] init];
        _titleLab.backgroundColor = [UIColor clearColor];
        _titleLab.font = [UIFont boldSystemFontOfSize:22];
        _titleLab.textColor = [UIColor whiteColor];
        _titleLab.textAlignment = NSTextAlignmentCenter;
        _titleLab.userInteractionEnabled = YES;
        
        [self.topView addSubview:_titleLab];
        
        UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showSelectCategoryView:)];
        [_titleLab addGestureRecognizer:tapGestureRecognizer];
    }
    
    return _titleLab;
}

- (UIImageView*)iconImageView {
    if (nil == _iconImageView) {
        _iconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"category_topBar_arr"]];
        _iconImageView.userInteractionEnabled = YES;
        _iconImageView.frame = CGRectMake(CGRectGetMaxX(self.titleLab.frame), 26, 23, 23);
        
        [self.topView addSubview:_iconImageView];
        
        UITapGestureRecognizer* tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showSelectCategoryView:)];
        [_iconImageView addGestureRecognizer:tapGestureRecognizer];
    }
    
    return _iconImageView;
}

- (UIControl*)closeCtrl {
    if (nil == _closeCtrl) {
        _closeCtrl = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds))];
        _closeCtrl.backgroundColor = [UIColor blackColor];
        _closeCtrl.alpha = .0;
        _closeCtrl.hidden = YES;
        [_closeCtrl addTarget:self action:@selector(onTapCloseCtrl:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_closeCtrl];
    }
    
    return _closeCtrl;
}

- (CategorySelectView*)selectView {
    if (nil == _selectView) {
        _selectView = [[CategorySelectView alloc] initWithFrame:CGRectMake(0, 57, CGRectGetWidth([UIScreen mainScreen].bounds), 0)];
        _selectView.hidden = YES;
        _selectView.tableView.delegate = self;
        _selectView.tableView.dataSource = self;
        [self.view insertSubview:_selectView aboveSubview:self.closeCtrl];
    }
    
    return _selectView;
}

- (CategoryFilterView*)filterView {
    if (nil == _filterView) {
        _filterView = [[CategoryFilterView alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.sortView.frame), CGRectGetMaxY(self.sortView.frame) - 1, CGRectGetWidth(self.sortView.frame), 0)];
        
        [_filterView setupCategoryFileterDefulte];
        [self.view insertSubview:_filterView aboveSubview:self.closeCtrl];
    }
    
    return _filterView;
}

#pragma mark - super
- (void)updateData {
    [super updateData];
    [self requestCategoryDataWithEngineModel:self.engineModel];
}

#pragma mark -
- (void)updateTitleViewFrame {
    self.titleLab.frame = [self.titleLab textRectForBounds:CGRectMake(0, 25, CGRectGetWidth([UIScreen mainScreen].bounds), 32) limitedToNumberOfLines:1];
    self.iconImageView.frame = CGRectMake(CGRectGetMaxX(self.titleLab.frame), 26, 23, 23);
}

- (void)requestCategoryDataWithEngineModel:(EngineModel*)model {
    if (_categoryOperation.isExecuting) {
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    
    NSString* path = [[CommonEngine sharedInstance] urlPathForDataWithDictionary:model.dic];
    
    _categoryOperation = [[CommonEngine sharedInstance] getOperationWithURLPath:path shouldCache:NO completionHandler:^(NSDictionary *result) {
        NSNumber* status = [result objectForKey:@"status"];
        NSNumber* count = [result objectForKey:@"count"];
        if (1 == status.integerValue) {
            
            NSMutableArray* res = [NSMutableArray new];
            
            NSArray* arr = [result objectForKey:@"res"];
            for (NSDictionary* dic in arr) {
                CommonCellModel* model = [[CommonCellModel alloc] initWithDic:dic];
                CommonCellViewModel* viewModel = [[CommonCellViewModel alloc] initWithCommonCellModel:model];
                [res addObject:viewModel];
            }
            
            if (weakSelf.engineModel.isNeedReloadData) {
                weakSelf.dataArr = res;
                weakSelf.engineModel.isNeedReloadData = NO;
            } else {
                [weakSelf.dataArr addObjectsFromArray:res];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
                if (weakSelf.sortView.isChangedSortCondition && 0 != count.integerValue) {
                    [weakSelf.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
                    weakSelf.tableView.reloadMoreView.statue = ReloadMoreDropupDroping;
                    weakSelf.sortView.isChangedSortCondition = NO;
                }
                
                [weakSelf.tableView resetReloadMoreViewFrame];
                if (TableViewUpdateTypeRefresh == weakSelf.tableView.type) {
                    [weakSelf finishRefreshData];
                } else if (TableViewUpdateTypeReloadMore == weakSelf.tableView.type) {
                    [weakSelf finishReloadMoreDataWithIsEnd:(0 == count.integerValue)];
                }
                
                weakSelf.viewControllerType = ViewControllerNormalType;
            });
        }
    } errorHandler:^(NSError *errMsg) {
        NSLog(@"%@", errMsg);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView resetReloadMoreViewFrame];
            if (TableViewUpdateTypeRefresh == weakSelf.tableView.type) {
                [weakSelf finishRefreshData];
            } else if (TableViewUpdateTypeReloadMore == weakSelf.tableView.type) {
                [weakSelf finishReloadMoreDataWithIsEnd:NO];
            }
            
            weakSelf.viewControllerType = ViewControllerNoNetWorkType;
        });
    }];
}

- (void)onTapCloseCtrl:(UIControl*)ctrl {
    [self closeCategorySelectView];
    [self closeCategoryFilterView];
}

- (void)showCategorySelectView {
    self.closeCtrl.hidden = NO;
    self.selectView.hidden = NO;
    
    self.selectView.posPoint = [self getPositionSubCategoryPoint];
    [self tableView:self.selectView.tableView didSelectRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectView.posPoint.x inSection:0]];
    [self.selectView.tableView reloadData];
    
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [UIView animateWithDuration:.5 animations:^{
        self.iconImageView.transform = CGAffineTransformMakeRotation(M_PI);
        self.closeCtrl.alpha = .3;
        
        CGRect frame = self.selectView.frame;
        frame.size.height = CGRectGetHeight([UIScreen mainScreen].bounds) - 57 - 47;
        self.selectView.frame = frame;
    } completion:^(BOOL finished) {
        
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    }];
}

- (void)closeCategorySelectView {
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [UIView animateWithDuration:.5 animations:^{
        self.iconImageView.transform = CGAffineTransformIdentity;
        self.closeCtrl.alpha = .0;
        
        CGRect frame = self.selectView.frame;
        frame.size.height = 0;
        self.selectView.frame = frame;
        
    } completion:^(BOOL finished) {
        self.closeCtrl.hidden = YES;
        self.selectView.hidden = YES;
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    }];
}

- (void)selectSubCategory:(NSNotification*)notify {
    SubCategoryModel* model = notify.object;
    self.categoryPos = CGPointMake(model.pidStr.integerValue, [model.pidStr isEqualToString:model.idStr]? 0 : model.idStr.integerValue);
    self.title = model.nameStr;
    
    [self closeCategorySelectView];
}

- (CGPoint)getPositionSubCategoryPoint {
    CGPoint point = CGPointZero;
    for (NSInteger index = 0; index < self.categoryArr.count; ++index) {
        NSDictionary* dic = [self.categoryArr objectAtIndex:index];
        NSString* name = [dic objectForKey:@"name"];
        if ([name isEqualToString:self.title]) {
            point = CGPointMake(index, 0);
            break;
        } else {
            BOOL isEqual = NO;
            NSArray* arr = [dic objectForKey:@"item"];
            for (NSDictionary* subDic in arr) {
                NSString* string = [subDic objectForKey:@"name"];
                if ([string isEqualToString:self.title]) {
                    NSString* idStr = [subDic objectForKey:@"id"];
                    point = CGPointMake(index, idStr.integerValue);
                    isEqual = YES;
                    break;
                }
            }
            
            if (isEqual) {
                break;
            }
        }
    }
    
    return point;
}

- (void)setupSortViewBtnsHandler {
    __weak typeof(self) weakSelf = self;
    
    self.sortView.tapDefulteBtnHandler = ^() {
        weakSelf.engineModel.pxStr = nil;
        weakSelf.engineModel.fyStr = nil;
        weakSelf.engineModel.adStr = nil;
        weakSelf.engineModel.isNeedUpdate = YES;
        [weakSelf closeCategoryFilterView];
        weakSelf.viewControllerType = ViewControllerLoadingType;
        weakSelf.tableView.reloadMoreView.statue = ReloadMoreDropupDroping;
    };
    
    self.sortView.tapSalesBtnHandler = ^() {
        if (![weakSelf.engineModel.pxStr isEqual:@"sellcount"]) {
            weakSelf.engineModel.pxStr = @"sellcount";
            weakSelf.engineModel.adStr = @"d";
        } else if ([weakSelf.engineModel.adStr isEqual:@"a"]) {
            weakSelf.engineModel.adStr = @"d";
        } else {
            weakSelf.engineModel.adStr = @"a";
        }
        
        weakSelf.engineModel.fyStr = nil;
        weakSelf.engineModel.isNeedUpdate = YES;
        [weakSelf closeCategoryFilterView];
        weakSelf.viewControllerType = ViewControllerLoadingType;
        weakSelf.tableView.reloadMoreView.statue = ReloadMoreDropupDroping;
    };
    
    self.sortView.tapPriceBtnHandler = ^() {
        if (![weakSelf.engineModel.pxStr isEqual:@"now_price"]) {
            weakSelf.engineModel.pxStr = @"now_price";
            weakSelf.engineModel.adStr = @"d";
        } else if ([weakSelf.engineModel.adStr isEqual:@"a"]) {
            weakSelf.engineModel.adStr = @"d";
        } else {
            weakSelf.engineModel.adStr = @"a";
        }
        
        weakSelf.engineModel.fyStr = nil;
        weakSelf.engineModel.isNeedUpdate = YES;
        [weakSelf closeCategoryFilterView];
        weakSelf.viewControllerType = ViewControllerLoadingType;
        weakSelf.tableView.reloadMoreView.statue = ReloadMoreDropupDroping;
    };
    
    self.sortView.tapFilterBtnHandler = ^() {
        if (0 == CGRectGetHeight(weakSelf.filterView.frame)) {
            [weakSelf showCategoryFilterView];
        } else {
            [weakSelf closeCategoryFilterView];
            
            if (weakSelf.engineModel.sxStr != weakSelf.filterView.filterString && ![weakSelf.engineModel.sxStr isEqualToString:weakSelf.filterView.filterString]) {
                weakSelf.engineModel.sxStr = weakSelf.filterView.filterString;
                weakSelf.engineModel.fyStr = @"1";
                weakSelf.engineModel.isNeedUpdate = YES;
                weakSelf.viewControllerType = ViewControllerLoadingType;
                
                weakSelf.sortView.isChangedSortCondition = YES;
            }
        }
    };
    
    [self.sortView setButtonsBorder];
}

- (void)showCategoryFilterView {
    self.closeCtrl.hidden = NO;
    
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [UIView animateWithDuration:.5 animations:^{
        CGRect frame = self.filterView.frame;
        frame.size.height = 173;
        self.filterView.frame = frame;
        
        self.closeCtrl.alpha = .3;
    } completion:^(BOOL finished) {
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    }];
}

- (void)closeCategoryFilterView {
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [UIView animateWithDuration:.5 animations:^{
        CGRect frame = self.filterView.frame;
        frame.size.height = 0;
        self.filterView.frame = frame;
        
        self.closeCtrl.alpha = 0;
    } completion:^(BOOL finished) {
        self.closeCtrl.hidden = YES;
        self.sortView.filterBtn.selected = NO;
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    }];
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"title"]) {
        self.titleLab.text = self.title;
        
        [self updateTitleViewFrame];
        
        //        CGPoint point = [self getPositionSubCategoryPoint];
        //        self.engineModel.flPoint = CGPointMake(point.x, point.y);
        self.engineModel.flPoint = self.categoryPos;
        self.engineModel.pxStr = nil;
        self.engineModel.fyStr = nil;
        self.engineModel.adStr = nil;
        self.engineModel.sxStr = nil;
        self.engineModel.isNeedUpdate = YES;
        
        self.sortView.isChangedSortCondition = YES;//分类切换时，tableview回到顶部，“加载更多”恢复默认状态
        
        self.viewControllerType = ViewControllerLoadingType;
        
        [self.filterView setupCategoryFileterDefulte];
    } else if ([keyPath isEqualToString:@"isNeedUpdate"]) {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - IBAction
- (IBAction)onTapBackBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)showSelectCategoryView:(id)sender {
    if (CGAffineTransformIsIdentity(self.iconImageView.transform)) {
        [self showCategorySelectView];
    } else {
        [self closeCategorySelectView];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:self.tableView]) {
        return self.dataArr.count;
    } else {
        return self.categoryArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:self.tableView]) {
        
        CommonTableViewCell *cell = (CommonTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"CategoryCell"];
        
        CommonCellViewModel* viewModel = [self.dataArr objectAtIndex:indexPath.row];
        [cell layoutSubviewDataWithViewModel:viewModel];
        
        return cell;
    } else {
        CategorySelectCell* cell = (CategorySelectCell*)[tableView dequeueReusableCellWithIdentifier:@"CategorySelectCell"];
        cell.pidStr = [NSString stringWithFormat:@"%zd", indexPath.row];
        
        NSDictionary* dic = [self.categoryArr objectAtIndex:indexPath.row];
        
        [cell layoutSubViewData:dic andIsSelect:(indexPath.row == self.showSubCategoryRow)];
        
        if (indexPath.row == self.selectView.posPoint.x) {
            NSString* name = [dic objectForKey:@"name"];
            if ([name isEqualToString:self.title]) {
                [cell.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
            } else {
                NSArray* itemsArr = [dic objectForKey:@"item"];
                for (NSInteger index = 0; index < itemsArr.count; ++index) {
                    NSDictionary* itemDic = [itemsArr objectAtIndex:index];
                    NSString* idStr = [itemDic objectForKey:@"id"];
                    if (idStr.integerValue == self.selectView.posPoint.y) {
                        [cell.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
                        break;
                    }
                }
            }
        }
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.tableView]) {
        return tableView.rowHeight;
    } else {
        if (indexPath.row == self.showSubCategoryRow && 0 != indexPath.row) {
            NSDictionary* dic = [self.categoryArr objectAtIndex:indexPath.row];
            NSArray* arr = [dic objectForKey:@"item"];
            return 48 * (arr.count + 1) + 1;
        } else {
            return 48;
        }
    }
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:self.tableView]) {
        CommonTableViewCell* cell = (CommonTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        if (cell.isSwiping) {
            return;
        }
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        CommonCellViewModel* viewModel = [self.dataArr objectAtIndex:indexPath.row];
        
        DetailViewController* controller = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
        controller.currentGoodsViewModel = viewModel;
        [self.navigationController pushViewController:controller animated:YES];
        
    } else {
        if (indexPath.row == self.showSubCategoryRow) {
            return;
        }
        
        if (0 == indexPath.row) {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            self.showSubCategoryRow = indexPath.row;
            NSDictionary* dic = [self.categoryArr objectAtIndex:indexPath.row];
            self.categoryPos = CGPointMake(0, 0);
            self.title = [dic objectForKey:@"name"];
            [self closeCategorySelectView];
        } else {
            NSIndexPath* oldPath = [NSIndexPath indexPathForRow:self.showSubCategoryRow inSection:0];
            self.showSubCategoryRow = indexPath.row;
            [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, oldPath, nil] withRowAnimation:UITableViewRowAnimationFade];
            
            [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
        
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if ([self.tableView isEqual:scrollView]) {
        [super scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if ([self.tableView isEqual:scrollView]) {
        [super scrollViewDidScroll:scrollView];
    }
}


#pragma mark - CategoryFilterViewDelegate
- (void)categoryFilterView:(CategoryFilterView *)categoryFilterView selectFilterConditionString:(NSString *)filterStr {
    
}

@end
